import Router from "koa-router";
import { authMiddleware } from "../../../middleware/auth";
import { pool } from "../../../config/database";
import { RowDataPacket, ResultSetHeader } from "mysql2";
import { 
  checkAdminPermission, 
  getPaginationParams, 
  createPaginatedResponse, 
  getSearchParams,
  handleError,
  successResponse,
  validateId,
  validateBatchIds
} from "../common";

const router = new Router({ prefix: "/api/admin/products" });

// JSON字段解析辅助函数
const parseJsonField = (field: any) => {
  if (!field) return null;
  if (typeof field === 'object') return field;
  try {
    return JSON.parse(field);
  } catch (e) {
    console.warn('JSON字段解析失败:', e);
    return null;
  }
};

// 默认features配置
const getDefaultFeatures = () => ([
  {
    id: 1,
    title: '高性能',
    description: '卓越的性能表现',
    icon: 'performance',
    highlight: true,
    order: 1
  },
  {
    id: 2,
    title: '易于安装',
    description: '简单快速的安装过程',
    icon: 'install',
    highlight: false,
    order: 2
  },
  {
    id: 3,
    title: '质量保证',
    description: '优质材料和工艺保障',
    icon: 'quality',
    highlight: true,
    order: 3
  }
]);

// 格式化产品数据，解析JSON字段
const formatProductData = (product: any) => {
  return {
    ...product,
    specifications: parseJsonField(product.specifications),
    features: parseJsonField(product.features) || [],
    images: parseJsonField(product.images),
    tags: parseJsonField(product.tags),
    dimensions: parseJsonField(product.dimensions),
    // 转换布尔值字段
    isFeatured: Boolean(product.isFeatured),
    isHot: Boolean(product.isHot)
  };
};

//获取产品配置信息
router.get("/:id/config", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;

  try {
    const id = validateId(ctx);
    if (id === null) return;

    const [products] = await pool.execute(
      "SELECT id, name, specifications FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    const product = products[0];
    const specifications = parseJsonField(product.specifications) || {};

    successResponse(ctx, {
      id: product.id,
      name: product.name,
      specifications: specifications
    }, "获取产品配置信息成功");

  } catch (error) {
    handleError(ctx, error, "获取产品配置信息失败");
  }
});

// 获取产品的核心特性配置
router.get("/:id/features", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const [products] = await pool.execute(
      "SELECT id, name, features FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    const product = products[0];
    const features = parseJsonField(product.features) || [];

    successResponse(ctx, {
      id: product.id,
      name: product.name,
      features: features
    }, "获取产品核心特性成功");

  } catch (error) {
    handleError(ctx, error, "获取产品核心特性失败");
  }
});

// 更新产品的核心特性配置
router.put("/:id/features", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const { features } = ctx.request.body as { features: any[] };

    if (!Array.isArray(features)) {
      ctx.status = 400;
      ctx.body = { success: false, message: "核心特性必须是数组格式" };
      return;
    }

    // 检查产品是否存在
    const [products] = await pool.execute(
      "SELECT id FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    // 处理不同格式的features数据
    let processedFeatures: any[] = [];
    
    if (features.length > 0) {
      // 检查第一个元素的类型来判断数据格式
      if (typeof features[0] === 'string') {
        // 字符串数组格式，转换为对象数组
        processedFeatures = features.map((feature: string, index: number) => ({
          id: index + 1,
          title: feature,
          description: '',
          icon: 'star',
          highlight: false,
          order: index + 1
        }));
      } else if (typeof features[0] === 'object' && features[0] !== null) {
        // 对象数组格式，验证必要字段
        for (let i = 0; i < features.length; i++) {
          const feature = features[i];
          if (!feature.title || typeof feature.title !== 'string') {
            ctx.status = 400;
            ctx.body = { success: false, message: `第${i + 1}个特性的标题不能为空` };
            return;
          }
        }
        processedFeatures = features;
      } else {
        ctx.status = 400;
        ctx.body = { success: false, message: "特性数据格式不正确，应为字符串数组或对象数组" };
        return;
      }
    }

    // 更新features配置
    await pool.execute(
      "UPDATE products SET features = ?, updated_at = NOW() WHERE id = ?",
      [JSON.stringify(processedFeatures), id]
    );

    successResponse(ctx, { 
      id, 
      features: processedFeatures 
    }, "更新产品核心特性成功");

  } catch (error) {
    handleError(ctx, error, "更新产品核心特性失败");
  }
});

// 添加产品核心特性
router.post("/:id/features", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const { title, description, icon, highlight = false } = ctx.request.body as {
      title: string;
      description?: string;
      icon?: string;
      highlight?: boolean;
    };

    if (!title || typeof title !== 'string') {
      ctx.status = 400;
      ctx.body = { success: false, message: "特性标题不能为空" };
      return;
    }

    // 检查产品是否存在并获取现有features
    const [products] = await pool.execute(
      "SELECT id, features FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    const currentFeatures = parseJsonField(products[0].features) || [];
    
    // 生成新的特性ID
    const newId = currentFeatures.length > 0 
      ? Math.max(...currentFeatures.map((f: any) => f.id || 0)) + 1 
      : 1;

    // 创建新特性
    const newFeature = {
      id: newId,
      title,
      description: description || '',
      icon: icon || 'star',
      highlight: Boolean(highlight),
      order: currentFeatures.length + 1
    };

    currentFeatures.push(newFeature);

    // 更新features配置
    await pool.execute(
      "UPDATE products SET features = ?, updated_at = NOW() WHERE id = ?",
      [JSON.stringify(currentFeatures), id]
    );

    successResponse(ctx, { 
      id, 
      feature: newFeature,
      features: currentFeatures
    }, "添加产品核心特性成功");

  } catch (error) {
    handleError(ctx, error, "添加产品核心特性失败");
  }
});

// 删除产品核心特性
router.delete("/:id/features/:featureId", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const featureId = parseInt(ctx.params.featureId);
    if (isNaN(featureId)) {
      ctx.status = 400;
      ctx.body = { success: false, message: "特性ID格式错误" };
      return;
    }

    // 检查产品是否存在并获取现有features
    const [products] = await pool.execute(
      "SELECT id, features FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    const currentFeatures = parseJsonField(products[0].features) || [];
    const featureIndex = currentFeatures.findIndex((f: any) => f.id === featureId);

    if (featureIndex === -1) {
      ctx.status = 404;
      ctx.body = { success: false, message: "特性不存在" };
      return;
    }

    // 删除特性
    currentFeatures.splice(featureIndex, 1);

    // 更新features配置
    await pool.execute(
      "UPDATE products SET features = ?, updated_at = NOW() WHERE id = ?",
      [JSON.stringify(currentFeatures), id]
    );

    successResponse(ctx, { 
      id, 
      featureId,
      features: currentFeatures
    }, "删除产品核心特性成功");

  } catch (error) {
    handleError(ctx, error, "删除产品核心特性失败");
  }
});

// 重置产品features为默认配置
router.post("/:id/features/reset", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    // 检查产品是否存在
    const [products] = await pool.execute(
      "SELECT id FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    const defaultFeatures = getDefaultFeatures();

    // 重置features配置
    await pool.execute(
      "UPDATE products SET features = ?, updated_at = NOW() WHERE id = ?",
      [JSON.stringify(defaultFeatures), id]
    );

    successResponse(ctx, { 
      id, 
      features: defaultFeatures 
    }, "重置产品核心特性成功");

  } catch (error) {
    handleError(ctx, error, "重置产品核心特性失败");
  }
});

// 获取商品列表 - 支持搜索和分页
router.get("/", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { page, limit, offset } = getPaginationParams(ctx);
    const { keyword, category, status, brand, minPrice, maxPrice, startDate, endDate, isFeatured, isHot } = getSearchParams(ctx);

    // 构建查询条件
    let whereClause = "WHERE 1=1";
    const params: any[] = [];

    if (keyword) {
      whereClause += " AND (name LIKE ? OR description LIKE ? OR brand LIKE ? OR model LIKE ? OR sku LIKE ?)";
      const searchTerm = `%${keyword}%`;
      params.push(searchTerm, searchTerm, searchTerm, searchTerm, searchTerm);
    }

    if (category) {
      whereClause += " AND category = ?";
      params.push(category);
    }

    if (status) {
      whereClause += " AND status = ?";
      params.push(status);
    }

    if (brand) {
      whereClause += " AND brand = ?";
      params.push(brand);
    }

    if (minPrice) {
      whereClause += " AND price >= ?";
      params.push(parseFloat(minPrice as string));
    }

    if (maxPrice) {
      whereClause += " AND price <= ?";
      params.push(parseFloat(maxPrice as string));
    }

    if (startDate) {
      whereClause += " AND created_at >= ?";
      params.push(startDate);
    }

    if (endDate) {
      whereClause += " AND created_at <= ?";
      params.push(endDate + ' 23:59:59');
    }

    if (isFeatured !== undefined) {
      whereClause += " AND isFeatured = ?";
      params.push(isFeatured === 'true' ? 1 : 0);
    }

    if (isHot !== undefined) {
      whereClause += " AND isHot = ?";
      params.push(isHot === 'true' ? 1 : 0);
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM products ${whereClause}`,
      params
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;

    // 获取商品列表 - 包含所有字段
    const [products] = await pool.execute(`
      SELECT 
        id, name, slug, category_id, brand, model, sku, 
        price, original_price, stock, sales, rating, review_count,
        short_description, description, specifications, features, 
        images, tags, status, category, isFeatured, isHot,
        meta_title, meta_description, weight, dimensions, warranty,
        created_at, updated_at
      FROM products 
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `, params) as [RowDataPacket[], any];

    // 格式化产品数据，解析JSON字段
    const formattedProducts = products.map(formatProductData);

    const response = createPaginatedResponse(formattedProducts, total, page, limit);
    successResponse(ctx, response, "获取商品列表成功");

  } catch (error) {
    handleError(ctx, error, "获取商品列表失败");
  }
});

// 获取产品配置列表 - 基于产品表的specifications和features字段
router.get("/configs", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { page, limit, offset } = getPaginationParams(ctx);
    const { keyword, category, minPrice, maxPrice, brand, status } = getSearchParams(ctx);

    // 构建查询条件
    let whereClause = "WHERE 1=1";
    const params: any[] = [];

    if (keyword) {
      whereClause += " AND (name LIKE ? OR description LIKE ? OR brand LIKE ?)";
      const searchTerm = `%${keyword}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }

    if (category) {
      whereClause += " AND category = ?";
      params.push(category);
    }

    if (brand) {
      whereClause += " AND brand = ?";
      params.push(brand);
    }

    if (status) {
      whereClause += " AND status = ?";
      params.push(status);
    }

    if (minPrice) {
      whereClause += " AND price >= ?";
      params.push(parseFloat(minPrice as string));
    }

    if (maxPrice) {
      whereClause += " AND price <= ?";
      params.push(parseFloat(maxPrice as string));
    }

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM products ${whereClause}`,
      params
    ) as [RowDataPacket[], any];
    const total = countResult[0].total;

    // 获取产品配置列表
    const [products] = await pool.execute(`
      SELECT 
        id, name, slug, brand, model, sku, price, original_price, 
        stock, sales, rating, review_count, category, status,
        short_description, description, specifications, features, 
        images, tags, isFeatured, isHot, created_at, updated_at
      FROM products 
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `, params) as [RowDataPacket[], any];

    // 格式化产品数据，解析JSON字段
    const formattedProducts = products.map(product => ({
      ...product,
      specifications: parseJsonField(product.specifications),
      features: parseJsonField(product.features),
      images: parseJsonField(product.images),
      tags: parseJsonField(product.tags),
      // 转换布尔值字段
      isFeatured: Boolean(product.isFeatured),
      isHot: Boolean(product.isHot)
    }));

    const response = createPaginatedResponse(formattedProducts, total, page, limit);
    successResponse(ctx, response, "获取产品配置列表成功");

  } catch (error) {
    handleError(ctx, error, "获取产品配置列表失败");
  }
});

// 获取产品的规格配置
router.get("/:id/specifications", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const [products] = await pool.execute(
      "SELECT id, name, specifications FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    const product = products[0];
    const specifications = parseJsonField(product.specifications) || {};

    successResponse(ctx, {
      id: product.id,
      name: product.name,
      specifications: specifications
    }, "获取产品规格配置成功");

  } catch (error) {
    handleError(ctx, error, "获取产品规格配置失败");
  }
});

// 更新产品的规格配置
router.put("/:id/specifications", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const { specifications } = ctx.request.body as { specifications: object };

    if (!specifications || typeof specifications !== 'object') {
      ctx.status = 400;
      ctx.body = { success: false, message: "规格配置数据格式错误" };
      return;
    }

    // 检查产品是否存在
    const [products] = await pool.execute(
      "SELECT id FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "产品不存在" };
      return;
    }

    // 更新规格配置
    await pool.execute(
      "UPDATE products SET specifications = ?, updated_at = NOW() WHERE id = ?",
      [JSON.stringify(specifications), id]
    );

    successResponse(ctx, { 
      id, 
      specifications 
    }, "更新产品规格配置成功");

  } catch (error) {
    handleError(ctx, error, "更新产品规格配置失败");
  }
});



// 获取商品详情
router.get("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const [products] = await pool.execute(
      "SELECT * FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "商品不存在" };
      return;
    }

    // 格式化产品数据，解析JSON字段
    const formattedProduct = formatProductData(products[0]);

    successResponse(ctx, formattedProduct, "获取商品详情成功");

  } catch (error) {
    handleError(ctx, error, "获取商品详情失败");
  }
});

// 创建商品
router.post("/", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { 
      name, slug, category_id, brand, model, sku,
      price, original_price, stock = 0, sales = 0,
      rating = 0, review_count = 0, short_description, description,
      specifications, features, images, tags,
      status = 'active', category = 'computer', 
      isFeatured = false, isHot = false,
      meta_title, meta_description, weight, dimensions, warranty
    } = ctx.request.body as {
      name: string;
      slug?: string;
      category_id?: number;
      brand: string;
      model?: string;
      sku?: string;
      price: number;
      original_price?: number;
      stock?: number;
      sales?: number;
      rating?: number;
      review_count?: number;
      short_description?: string;
      description?: string;
      specifications?: object;
      features?: object;
      images?: object;
      tags?: object;
      tabs?: object;
      status?: string;
      category?: string;
      isFeatured?: boolean;
      isHot?: boolean;
      meta_title?: string;
      meta_description?: string;
      weight?: number;
      dimensions?: object;
      warranty?: string;
    };

    // 参数验证
    if (!name || !brand || price === undefined) {
      ctx.status = 400;
      ctx.body = { success: false, message: "商品名称、品牌和价格为必填项" };
      return;
    }

    if (price <= 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "价格必须大于0" };
      return;
    }

    // 如果未提供 category_id，设置默认值为 1
    const finalCategoryId = category_id || 1;

    // 生成slug（如果未提供）
    const productSlug = slug || name.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-');

    // 检查slug唯一性
    if (productSlug) {
      const [existingSlugs] = await pool.execute(
        "SELECT id FROM products WHERE slug = ?",
        [productSlug]
      ) as [RowDataPacket[], any];

      if (existingSlugs.length > 0) {
        ctx.status = 400;
        ctx.body = { success: false, message: "商品别名已存在" };
        return;
      }
    }

    // 创建商品 - 确保所有undefined值转换为null
    const [result] = await pool.execute(
      `INSERT INTO products 
       (name, slug, category_id, brand, model, sku, price, original_price, 
        stock, sales, rating, review_count, short_description, description,
        specifications, features, images, tags, status, category,
        isFeatured, isHot, meta_title, meta_description, weight, dimensions, warranty) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        name, 
        productSlug, 
        finalCategoryId, 
        brand, 
        model || null, 
        sku || null, 
        price, 
        original_price || price, 
        stock || 0, 
        sales || 0, 
        rating || 0, 
        review_count || 0,
        short_description || null, 
        description || null,
        specifications ? JSON.stringify(specifications) : null,
        features ? JSON.stringify(features) : null,
        images ? JSON.stringify(images) : null,
        tags ? JSON.stringify(tags) : null,
        status || 'active', 
        category || 'computer', 
        isFeatured ? 1 : 0, 
        isHot ? 1 : 0,
        meta_title || null, 
        meta_description || null, 
        weight || null,
        dimensions ? JSON.stringify(dimensions) : null,
        warranty || null
      ]
    ) as [ResultSetHeader, any];

    const [newProduct] = await pool.execute(
      "SELECT * FROM products WHERE id = ?",
      [result.insertId]
    ) as [RowDataPacket[], any];

    // 格式化返回数据
    const formattedProduct = formatProductData(newProduct[0]);

    successResponse(ctx, formattedProduct, "商品创建成功");

  } catch (error) {
    handleError(ctx, error, "创建商品失败");
  }
});

// 创建产品配置 - 基于产品表
router.post("/configs", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const { 
      name, brand, model, sku, price, original_price, stock = 0,
      category = 'computer', short_description, description, 
      specifications, features, images, tags,
      isFeatured = false, isHot = false, status = 'active'
    } = ctx.request.body as {
      name: string;
      brand?: string;
      model?: string;
      sku?: string;
      price: number;
      original_price?: number;
      stock?: number;
      category?: string;
      short_description?: string;
      description?: string;
      specifications?: object;
      features?: object;
      images?: object;
      tags?: object;
      isFeatured?: boolean;
      isHot?: boolean;
      status?: string;
    };

    if (!name || price === undefined) {
      ctx.status = 400;
      ctx.body = { success: false, message: "产品名称和价格为必填项" };
      return;
    }

    if (price <= 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "价格必须大于0" };
      return;
    }

    // 生成slug
    const slug = name.toLowerCase().replace(/[^a-z0-9]/g, '-').replace(/-+/g, '-');

    // 检查slug唯一性
    const [existingSlugs] = await pool.execute(
      "SELECT id FROM products WHERE slug = ?",
      [slug]
    ) as [RowDataPacket[], any];

    if (existingSlugs.length > 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "产品名称重复，请使用不同的名称" };
      return;
    }

    // 创建产品配置 - 确保所有undefined值转换为null，添加默认category_id
    const [result] = await pool.execute(
      `INSERT INTO products 
       (name, slug, category_id, brand, model, sku, price, original_price, stock, 
        category, short_description, description, specifications, features, 
        images, tags, status, isFeatured, isHot) 
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        name, 
        slug, 
        1, // 默认 category_id
        brand || null, 
        model || null, 
        sku || null, 
        price, 
        original_price || price, 
        stock || 0,
        category || 'computer', 
        short_description || null, 
        description || null,
        specifications ? JSON.stringify(specifications) : null,
        features ? JSON.stringify(features) : null,
        images ? JSON.stringify(images) : null,
        tags ? JSON.stringify(tags) : null,
        status || 'active', 
        isFeatured ? 1 : 0, 
        isHot ? 1 : 0
      ]
    ) as [ResultSetHeader, any];

    const [newProduct] = await pool.execute(
      "SELECT * FROM products WHERE id = ?",
      [result.insertId]
    ) as [RowDataPacket[], any];

    // 格式化返回数据
    const formattedProduct = formatProductData(newProduct[0]);

    successResponse(ctx, formattedProduct, "产品配置创建成功");

  } catch (error) {
    handleError(ctx, error, "创建产品配置失败");
  }
});

// 更新商品
router.put("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const updateData = ctx.request.body as {
      name?: string;
      slug?: string;
      category_id?: number;
      brand?: string;
      model?: string;
      sku?: string;
      price?: number;
      original_price?: number;
      stock?: number;
      sales?: number;
      rating?: number;
      review_count?: number;
      short_description?: string;
      description?: string;
      specifications?: object;
      features?: object;
      images?: object;
      tags?: object;
      tabs?: object;
      status?: string;
      category?: string;
      isFeatured?: boolean;
      isHot?: boolean;
      meta_title?: string;
      meta_description?: string;
      weight?: number;
      dimensions?: object;
      warranty?: string;
    };

    // 检查商品是否存在
    const [products] = await pool.execute(
      "SELECT id FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "商品不存在" };
      return;
    }

    // 检查slug唯一性
    if (updateData.slug) {
      const [existingSlugs] = await pool.execute(
        "SELECT id FROM products WHERE slug = ? AND id != ?",
        [updateData.slug, id]
      ) as [RowDataPacket[], any];

      if (existingSlugs.length > 0) {
        ctx.status = 400;
        ctx.body = { success: false, message: "商品别名已存在" };
        return;
      }
    }

    // 构建更新语句
    const updateFields: string[] = [];
    const updateValues: any[] = [];

          Object.keys(updateData).forEach(key => {
        const value = updateData[key as keyof typeof updateData];
        if (value !== undefined) {
          // 处理JSON字段
          if (['specifications', 'features', 'images', 'tags', 'dimensions'].includes(key)) {
            updateFields.push(`${key} = ?`);
            updateValues.push(value ? JSON.stringify(value) : null);
          }
          // 处理布尔字段
          else if (['isFeatured', 'isHot'].includes(key)) {
            updateFields.push(`${key} = ?`);
            updateValues.push(value ? 1 : 0);
          }
                   // 处理普通字段
           else {
             // 价格验证
             if (key === 'price' && typeof value === 'number' && value <= 0) {
               ctx.status = 400;
               ctx.body = { success: false, message: "价格必须大于0" };
               return;
             }
             updateFields.push(`${key} = ?`);
             updateValues.push(value);
           }
        }
      });

    if (updateFields.length === 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "没有提供要更新的字段" };
      return;
    }

    updateFields.push("updated_at = NOW()");
    updateValues.push(id);

    // 执行更新
    await pool.execute(
      `UPDATE products SET ${updateFields.join(", ")} WHERE id = ?`,
      updateValues
    );

    const [updatedProduct] = await pool.execute(
      "SELECT * FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    // 格式化返回数据
    const formattedProduct = formatProductData(updatedProduct[0]);

    successResponse(ctx, formattedProduct, "商品更新成功");

  } catch (error) {
    handleError(ctx, error, "更新商品失败");
  }
});

// 更新库存
router.post("/:id/update-stock", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    const { stock, operation = 'set' } = ctx.request.body as {
      stock: number;
      operation?: 'set' | 'add' | 'subtract';
    };

    if (stock === undefined || stock < 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "库存数量不能为负数" };
      return;
    }

    // 检查商品是否存在
    const [products] = await pool.execute(
      "SELECT id, stock FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "商品不存在" };
      return;
    }

    let newStock = stock;
    const currentStock = products[0].stock;

    switch (operation) {
      case 'add':
        newStock = currentStock + stock;
        break;
      case 'subtract':
        newStock = currentStock - stock;
        if (newStock < 0) {
          ctx.status = 400;
          ctx.body = { success: false, message: "库存不足，无法减少" };
          return;
        }
        break;
      case 'set':
      default:
        newStock = stock;
        break;
    }

    // 更新库存
    await pool.execute(
      "UPDATE products SET stock = ?, updated_at = NOW() WHERE id = ?",
      [newStock, id]
    );

    successResponse(ctx, { 
      id, 
      oldStock: currentStock, 
      newStock, 
      operation 
    }, "库存更新成功");

  } catch (error) {
    handleError(ctx, error, "更新库存失败");
  }
});

// 批量更新商品状态
router.post("/batch-update-status", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const ids = validateBatchIds(ctx);
    if (ids === null) return;

    const { status } = ctx.request.body as { status: string };

    if (!status) {
      ctx.status = 400;
      ctx.body = { success: false, message: "状态不能为空" };
      return;
    }

    const [result] = await pool.execute(
      `UPDATE products SET status = ?, updated_at = NOW() WHERE id IN (${ids.map(() => '?').join(',')})`,
      [status, ...ids]
    ) as [ResultSetHeader, any];

    successResponse(ctx, { 
      updatedCount: result.affectedRows,
      status 
    }, `批量更新状态成功，影响${result.affectedRows}个商品`);

  } catch (error) {
    handleError(ctx, error, "批量更新状态失败");
  }
});

// 批量更新特色/热门标记
router.post("/batch-update-flags", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const ids = validateBatchIds(ctx);
    if (ids === null) return;

    const { isFeatured, isHot } = ctx.request.body as { 
      isFeatured?: boolean; 
      isHot?: boolean; 
    };

    if (isFeatured === undefined && isHot === undefined) {
      ctx.status = 400;
      ctx.body = { success: false, message: "请提供要更新的标记" };
      return;
    }

    const updateFields: string[] = [];
    const updateValues: any[] = [];

    if (isFeatured !== undefined) {
      updateFields.push("isFeatured = ?");
      updateValues.push(isFeatured ? 1 : 0);
    }

    if (isHot !== undefined) {
      updateFields.push("isHot = ?");
      updateValues.push(isHot ? 1 : 0);
    }

    updateFields.push("updated_at = NOW()");
    updateValues.push(...ids);

    const [result] = await pool.execute(
      `UPDATE products SET ${updateFields.join(", ")} WHERE id IN (${ids.map(() => '?').join(',')})`,
      updateValues
    ) as [ResultSetHeader, any];

    successResponse(ctx, { 
      updatedCount: result.affectedRows,
      isFeatured,
      isHot
    }, `批量更新标记成功，影响${result.affectedRows}个商品`);

  } catch (error) {
    handleError(ctx, error, "批量更新标记失败");
  }
});

// 删除商品
router.delete("/:id", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const id = validateId(ctx);
    if (id === null) return;

    // 检查商品是否存在
    const [products] = await pool.execute(
      "SELECT id FROM products WHERE id = ?",
      [id]
    ) as [RowDataPacket[], any];

    if (products.length === 0) {
      ctx.status = 404;
      ctx.body = { success: false, message: "商品不存在" };
      return;
    }

    // 检查是否有未完成的订单使用此商品
    const [orderItems] = await pool.execute(
      `SELECT COUNT(*) as count FROM order_items oi 
       JOIN orders o ON oi.order_id = o.id 
       WHERE oi.product_id = ? AND o.status NOT IN ('cancelled', 'completed')`,
      [id]
    ) as [RowDataPacket[], any];

    if (orderItems[0].count > 0) {
      ctx.status = 400;
      ctx.body = { success: false, message: "该商品有未完成的订单，无法删除" };
      return;
    }

    // 删除商品
    await pool.execute("DELETE FROM products WHERE id = ?", [id]);

    successResponse(ctx, { id }, "商品删除成功");

  } catch (error) {
    handleError(ctx, error, "删除商品失败");
  }
});

// 获取商品统计信息
router.get("/statistics/overview", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    // 商品总体统计
    const [productStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_products,
        COUNT(CASE WHEN status = 'active' THEN 1 END) as active_products,
        COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive_products,
        COUNT(CASE WHEN status = 'discontinued' THEN 1 END) as discontinued_products,
        COUNT(CASE WHEN stock = 0 THEN 1 END) as out_of_stock,
        COUNT(CASE WHEN stock > 0 AND stock <= 10 THEN 1 END) as low_stock,
        COUNT(CASE WHEN isFeatured = 1 THEN 1 END) as featured_products,
        COUNT(CASE WHEN isHot = 1 THEN 1 END) as hot_products,
        AVG(price) as avg_price,
        SUM(stock) as total_stock,
        AVG(rating) as avg_rating,
        SUM(sales) as total_sales
      FROM products
    `) as [RowDataPacket[], any];

    // 配置统计
    const [configStats] = await pool.execute(`
      SELECT 
        COUNT(*) as total_configs,
        AVG(total_price) as avg_config_price,
        AVG(performance_score) as avg_performance_score
      FROM configs
    `) as [RowDataPacket[], any];

    // 热门类别统计
    const [categoryStats] = await pool.execute(`
      SELECT 
        category,
        COUNT(*) as product_count,
        AVG(price) as avg_price,
        SUM(sales) as total_sales
      FROM products
      GROUP BY category
      ORDER BY product_count DESC
      LIMIT 10
    `) as [RowDataPacket[], any];

    // 热门品牌统计
    const [brandStats] = await pool.execute(`
      SELECT 
        brand,
        COUNT(*) as product_count,
        AVG(price) as avg_price,
        SUM(sales) as total_sales
      FROM products
      WHERE brand IS NOT NULL AND brand != ''
      GROUP BY brand
      ORDER BY product_count DESC
      LIMIT 10
    `) as [RowDataPacket[], any];

    // 价格区间统计
    const [priceRangeStats] = await pool.execute(`
      SELECT 
        CASE 
          WHEN price < 100 THEN '0-99'
          WHEN price < 500 THEN '100-499'
          WHEN price < 1000 THEN '500-999'
          WHEN price < 2000 THEN '1000-1999'
          WHEN price < 5000 THEN '2000-4999'
          ELSE '5000+'
        END as price_range,
        COUNT(*) as product_count
      FROM products
      GROUP BY price_range
      ORDER BY MIN(price)
    `) as [RowDataPacket[], any];

    successResponse(ctx, {
      products: productStats[0],
      configs: configStats[0],
      categories: categoryStats,
      brands: brandStats,
      priceRanges: priceRangeStats
    }, "获取商品统计成功");

  } catch (error) {
    handleError(ctx, error, "获取商品统计失败");
  }
});

// 获取品牌列表
router.get("/brands/list", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const [brands] = await pool.execute(`
      SELECT 
        brand,
        COUNT(*) as product_count
      FROM products
      WHERE brand IS NOT NULL AND brand != ''
      GROUP BY brand
      ORDER BY brand ASC
    `) as [RowDataPacket[], any];

    successResponse(ctx, brands, "获取品牌列表成功");

  } catch (error) {
    handleError(ctx, error, "获取品牌列表失败");
  }
});

// 获取类别列表
router.get("/categories/list", authMiddleware, async (ctx) => {
  if (!checkAdminPermission(ctx)) return;
  
  try {
    const [categories] = await pool.execute(`
      SELECT 
        category,
        COUNT(*) as product_count
      FROM products
      WHERE category IS NOT NULL AND category != ''
      GROUP BY category
      ORDER BY category ASC
    `) as [RowDataPacket[], any];

    successResponse(ctx, categories, "获取类别列表成功");

  } catch (error) {
    handleError(ctx, error, "获取类别列表失败");
  }
});

export default router; 